package com.ycz.sas.jgen.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

public class JdbcDAO implements BaseDAO{
	
	private DataSource dataSource;
	
	public void setDataSource(DataSource dataSource){
		this.dataSource = dataSource;
	}

	@Override
	public void execute(String sql) {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.executeUpdate();
			ps.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
 
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {}
			}
		}
	}

	@Override
	public void execute(String sql, Object[] param) {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			for (int i = 0; i < param.length; i++) {
				ps.setObject(i + 1, param[i]);
			}
			ps.executeUpdate();
			ps.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
 
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {}
			}
		}
	}

	@Override
	public ResultSet executeQuery(String sql) {
		Connection conn = null;
		ResultSet st = null;
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			st = ps.executeQuery(sql);
		} catch (SQLException e) {
			throw new RuntimeException(e);
 
		} finally {
		}
		return st;
	}

	@Override
	public ResultSet executeQuery(String sql, Object[] param) {
		Connection conn = null;
		ResultSet st = null;
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			for (int i = 0; i < param.length; i++) {
				Object p = param[i];
				if(p instanceof String)
					ps.setString(i + 1, (String)p);
				else if (p instanceof Integer)
					ps.setInt(i + 1, (Integer)p);
				else if (p instanceof Double)
					ps.setDouble(i + 1, (Double)p);
				else if (p instanceof Float)
					ps.setFloat(i + 1, (Float)p);
				else if (p instanceof Long)
					ps.setLong(i + 1, (Long)p);
				else if (p instanceof Date)
					ps.setDate(i + 1, (Date)p);
				else
					ps.setObject(i + 1, p);
			}
			st = ps.executeQuery(sql);
		} catch (SQLException e) {
			throw new RuntimeException(e);
 
		} finally {
		}
		return st;
	}
	
	public void close(){
		
	}

}
